package com.qingcheng.controller;


import com.alibaba.fastjson.JSON;
import com.qingcheng.entity.Result;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author lin.jia
 * 定义一个切面
 */
@Aspect
@Configuration
public class LogRecordAspect {
    final static String CLASS_NAME = "org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice.supports";

    private final static Logger logger = LoggerFactory.getLogger(LogRecordAspect.class);

    /**
     * ..表示包及子包 该方法代表controller层的所有方法
     */
    @Pointcut("execution(public * com.qingcheng.controller.*.*(..))")
    public void controllerMethod() {
    }


    @Before("controllerMethod()")
    public void logRequestInfo(JoinPoint joinPoint) throws Exception {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        StringBuilder requestLog = new StringBuilder();
        requestLog.append("请求信息：").append("URL = {").append(request.getRequestURI()).append("},").append("HTTP_METHOD = {").append(request.getMethod()).append("},").append("IP = {").append(request.getRemoteAddr()).append("},");
        if (request.getParameterMap().size() > 0) {
            requestLog.append("Parameters:").append(JSON.toJSONString(request.getParameterMap()));
        }
        //过滤Spring包装结果类
        String anObject = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        if (CLASS_NAME.equals(anObject)) {
            logger.info(requestLog.toString());
        }
    }


    @AfterReturning(returning = "resultVO", pointcut = "controllerMethod()")
    public void logResultVoInfo(Result resultVO) {
        logger.info("请求结果：" + resultVO);
    }

}
